package com.wy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.wy.common.BaseContext;
import com.wy.common.CustomException;
import com.wy.entity.*;
import com.wy.mapper.OrderMapper;
import com.wy.service.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
     @Autowired
     private ShoppingCartService shoppingCartService;
     @Autowired
     private UserService userService;
     @Autowired
     private AddressBookService addressBookService;
     @Autowired
     private OrderDetailService orderDetailService;

    /**
     * 用户下单
     */
    @Transactional
    public void submit(Orders orders) {
        //1.获取用户id
        Long userId = BaseContext.getCurrentId();
        //2.获取用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
            //判断购物车是否为空
            if(shoppingCartList == null || shoppingCartList.size() == 0){
                throw new CustomException("购物车为空,不能下单哦~~快去商品列表添加几件哦~~");
            }
            //获取用户的信息
            User user = userService.getById(userId);
            //获取用户的地址
            AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
            //判断地址是否为空
            if(addressBook == null ){
                throw new CustomException("用户地址信息为空,不能下单~");
            }

        //3.将购物车的数据添加到订单表中,一条

            long orderId = IdWorker.getId();//订单号
            AtomicInteger amount = new AtomicInteger(0);

            //订单的金额,将购物车里的所有金额遍历累加
            List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(item.getNumber());
                orderDetail.setDishFlavor(item.getDishFlavor());
                orderDetail.setDishId(item.getDishId());
                orderDetail.setSetmealId(item.getSetmealId());
                orderDetail.setName(item.getName());
                orderDetail.setImage(item.getImage());
                orderDetail.setAmount(item.getAmount());
                amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
                    return orderDetail;
            }).collect(Collectors.toList());

            //需要补充对应的订单信息
            orders.setId(orderId);
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(LocalDateTime.now());
            orders.setStatus(2);
            orders.setAmount(new BigDecimal(amount.get()));//总金额
            orders.setUserId(userId);
            orders.setNumber(String.valueOf(orderId));
            orders.setUserName(user.getName());
            orders.setConsignee(addressBook.getConsignee());
            orders.setPhone(addressBook.getPhone());
            orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                    + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                    + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                    + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);
        //4.蒋订单的内容添加到订单明细表中,多条
        orderDetailService.saveBatch(orderDetails);
        //5.清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
